<template>
  <div id="PersonnelAndManagement" v-loading="showLoading">
    <cus-Breadcrumb level1="用户与权限" level2="用户角色配置" class="mb20"></cus-Breadcrumb>
    <el-card>
      <el-button @click="addNew" v-if="yhyhAdd">添加新用户</el-button>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column label="姓名" prop="userName"></el-table-column>
        <el-table-column label="角色" prop="userRole">
          <template slot-scope="scope">
            <el-button size="mini" @click="queryByManagerId(scope.$index, scope.row)" v-if="yhyhSearch">查询角色与权限</el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="name">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.$index, scope.row);flipListForRole (scope.$index, scope.row)"
              v-if="yhyhBind"
            >绑定角色</el-button>
            <el-button type="danger" size="mini" @click="removeItem(scope.$idnex, scope.row)" v-if="yhyhDelete">删除此用户</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog title="查看角色与权限" :visible.sync="searchFlag" class="dialogAdd">
      <table class="r-p-table" cellspacing="0">
        <thead>
          <th>角色名</th>
          <th>权限名</th>
        </thead>
        <tbody>
          <tr>
            <td class="td">
              <el-tag class="jsm" v-for="(item, index) in userName" :key="index">{{userName[index]}}</el-tag>
            </td>
            <td>
              <el-tag
                v-for="(item, ind) in userRole"
                :key="ind"
                class="permissions"
              >{{userRole[ind]}}</el-tag>
            </td>
          </tr>
        </tbody>
      </table>
    </el-dialog>
    <el-dialog title="绑定角色" :visible.sync="editFlag" class="dialogAdd">
      <el-transfer
        v-model="value5"
        :props="{
      key: 'value',
      label: 'desc',
    }"
        :titles="['未绑定角色', '已绑定角色']"
        :data="data3"
      ></el-transfer>
      <el-button type="primary" class="commitChange" @click="commitChang()">提交更改</el-button>
    </el-dialog>
  </div>
</template>
<script>
import $$ from '@/plugins/statusCode.config'
export default {
  data () {
    return {
      yhyhAdd: false,
      yhyhSearch: false,
      yhyhBind: false,
      yhyhDelete: false,
      showLoading: false,
      searchFlag: false,
      tableData: [],
      data3: [],
      value5: [],
      editFlag: false,
      managerId: '',
      userRole: [],
      arr: [],
      value: [],
      userName: []
    }
  },
  beforeCreate () {
    // this.managerSearchFlipList()
  },
  created () {
    this.showLoading = true
    this.managerSearchFlipList()
  },
  mounted () {
    this.role()
  },
  methods: {
    role () {
      let arr = JSON.parse(sessionStorage.getItem('buttonRole'))
      for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 'yhyh-add') {
          this.yhyhAdd = true
        }
        if (arr[i] === 'yhyh-search') {
          this.yhyhSearch = true
        }
        if (arr[i] === 'yhyh-bind') {
          this.yhyhBind = true
        }
        if (arr[i] === 'yhyh-delete') {
          this.yhyhDelete = true
        }
      }
    },
    addNew () {
      this.$confirm(
        '即将跳转至企业管理页面，需要从企业列表中选出企业成员指定其为用户',
        '温馨提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$router.push({ name: 'HandleEnterpriseList' })
          this.$message.success('进入到查询企业列表')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消跳转'
          })
        })
    },
    removeItem (index, row) {
      const id = row.id
      const that = this
      let param = new URLSearchParams()
      param.append('id', id)
      this.$http8080
        .post('/manager-operate/removeById', param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20004) {
            that.$message.success(res.data.statusMsg)
            that.managerSearchFlipList()
          } else {
            that.$message.error(res.data.statusMsg)
          }
        })
    },
    handleEdit (index, row) {
      this.editFlag = true
      this.managerId = row.id
    },
    async managerSearchFlipList () {
      const that = this
      let param = new URLSearchParams()
      param.append(
        'departmentCode',
        sessionStorage.getItem('departmentCode') !== 'null'
          ? sessionStorage.getItem('departmentCode')
          : 1
      )
      await this.$http8081
        .post('/manager-search/flipList', param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20006) {
            that.showLoading = false
            that.tableData = res.data.data.records
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.managerSearchFlipList()
                }
              })
          }
        })
    },
    async queryByManagerId (index, row) {
      const rows = row
      this.searchFlag = true
      const that = this
      const param = new URLSearchParams()
      param.append('managerId', rows.id)
      await this.$http8081
        .post(
          '/authorization-search/queryAuthorizationAndRoleByManagerId',
          param
        )
        .then(function (res) {
          that.value = []
          if (res.data.statusCode === $$.s20006) {
            that.userRole = res.data.data.authorizationName
            that.userName = res.data.data.roleName
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.queryByManagerId(null, rows)
                }
              })
          }
        })
    },
    async flipListForRole (index, row) {
      const rows = row
      this.showLoading = true
      const that = this
      await this.$http8081
        .post('/authorization-search/flipListForRole')
        .then(function (res) {
          const swapRoleArr = []
          if (res.data.statusCode === $$.s20006) {
            that.showLoading = false
            that.data3 = []
            const data = res.data.data.records
            for (let i = 0; i < data.length; i++) {
              that.data3.push({
                value: data[i].id,
                desc: data[i].roleName
              })
              swapRoleArr.push({
                id: data[i].id,
                roleName: data[i].roleName
              })
            }
            let arr = []
            const param = new URLSearchParams()
            param.append('managerId', rows.id)
            that.$http8081
              .post(
                '/authorization-search/queryAuthorizationAndRoleByManagerId',
                param
              )
              .then(function (res) {
                that.value = []
                if (res.data.statusCode === $$.s20006) {
                  that.showLoading = false
                  for (let i = 0; i < res.data.data.roleName.length; i++) {
                    that.value.push(i)
                    arr.push(res.data.data.roleName[i])
                  }
                  for (let k = 0; k < arr.length; k++) {
                    for (let p = 0; p < swapRoleArr.length; p++) {
                      if (arr[k] === swapRoleArr[p].roleName) {
                        that.value5.push(swapRoleArr[p].id)
                      }
                    }
                  }
                  that.userRole = arr
                }
              })
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.flipListForRole(null, rows)
                }
              })
          }
        })
    },
    async commitChang () {
      this.showLoading = true
      const roleIds = this.value5.join()
      const that = this
      let param = new URLSearchParams()
      param.append('roleIds', roleIds)
      param.append('managerId', this.managerId)
      await this.$http8080
        .post('/authorization-operate/bindManager', param)
        .then(function (res) {
          if (res.data.statusCode === $$.s20000) {
            that.showLoading = false
            that.$message.success(res.data.statusMsg)
            that.value5 = []
            that.data3 = []
            that.editFlag = false
          } else {
            that.$message.error(res.data.statusMsg)
          }
          if (res.data.statusCode === $$.s70003) {
            const id = sessionStorage.getItem('id')
            let param = new URLSearchParams()
            param.append('id', id)
            const _that = that
            return that.$refresh
              .post(`/manager-search/updateToken`, param)
              .then(function (res) {
                if (res.data.statusCode === $$.s70005) {
                  sessionStorage.setItem(
                    'accessToken',
                    res.data.data.accessToken
                  )
                  sessionStorage.setItem(
                    'refreshToken',
                    res.data.data.refreshToken
                  )
                  _that.commitChang()
                }
              })
          }
        })
    }
  }
}
</script>
<style scope="scoped">
.el-tag-box {
  margin-bottom: 30px;
  height: 40px;
  line-height: 40px;
}
.r-p-table {
  font-size: 20px;
}
.r-p-table tbody td {
  width: 400px;
  height: 30px;
  line-height: 30px;
  padding-left: 15px;
  margin-top: 30px;
}
.r-p-table tbody span {
  margin-top: 10px;
  margin-right: 5px;
}
.r-p-table tbody .jsm {
  text-align: center;
}
.r-p-table .td {
  text-align: center;
}
</style>
